import 'dart:io';

import 'package:dart_console/dart_console.dart';

class TUI {
  final Console console = Console();
  final StringBuffer logBuffer = StringBuffer();
  File? logFile;

  void setLogFile(File file) {
    logFile = file;
  }

  void log(String message) {
    final line = '[${DateTime.now().toIso8601String()}] $message';
    logBuffer.writeln(line);
    stdout.writeln(line);
    logFile?.writeAsStringSync('$line\n', mode: FileMode.append);
  }

  void updateTask(String taskName, int percent) {
    console.clearScreen();

    // Top bar
    console.setBackgroundColor(ConsoleColor.black);
    console.setForegroundColor(ConsoleColor.white);
    console.writeLine(
        ' Cosmic Resource Downloader '.padRight(console.windowWidth));
    console.resetColorAttributes();
    console.writeLine('');

    // Task & Progress
    final progressWidth = console.windowWidth ~/ 2 - 20;
    final filled = (percent * progressWidth / 100).toInt();
    final bar = '█' * filled + '░' * (progressWidth - filled);
    console
        .write('🎯 Current Task: $taskName'.padRight(console.windowWidth ~/ 2));
    console.writeLine('📊 Progress: $bar ${percent}%');
    console.writeLine('');

    // Log area (last 10 lines)
    final logLines = logBuffer.toString().split('\n');
    final recentLogs =
        logLines.take(logLines.length > 10 ? 10 : logLines.length).toList();

    console.setForegroundColor(ConsoleColor.brightBlack);
    for (final line in recentLogs) {
      if (line.contains('❌')) {
        console.setForegroundColor(ConsoleColor.red);
        console.writeLine(line);
        console.setForegroundColor(ConsoleColor.brightBlack);
      } else if (line.contains('✅')) {
        console.setForegroundColor(ConsoleColor.green);
        console.writeLine(line);
        console.setForegroundColor(ConsoleColor.yellow);
      } else {
        console.writeLine(line);
      }
    }
    console.resetColorAttributes();
  }
}
